<template>
    <view class="record" style="position: fixed">
        <course-index type="record-1"></course-index>
        <course-index type="record-2" v-if="record_status==1"></course-index>
        <!--<course-index type="record-3" v-if="record_status==1"></course-index>-->
        <!--<course-index type="record-4" v-if="dialog_save"></course-index>-->
        <uni-swiper-dot  :info="info" :current="current" :dots-styles="dotsStyles" field="content" :mode="mode">
            <swiper class="swiper-box" @change="change" :style="{height: swiperHeight}">
                <swiper-item  v-for="(item ,index) in info" :key="index">
                    <image :src="item.url" style="width: 750upx; height: 1206upx;" :class="ipad" mode="scaleToFill"></image>
                </swiper-item>
            </swiper>
        </uni-swiper-dot>
        <view class="button_box button_begin" v-if="record_status==0" @click="beginRecord">
            <view class="button_box_list">
                <view class="button button_b">
                    <text class="iconfont begin_r">&#xe61a;</text>
                </view>
                <text class="button_b_t font-medium">开始录制</text>
                <text class="button_s_t"></text>
            </view>
        </view>
        <view class="button_box" v-if="record_status>0">
            <!--<view class="button_box_list relative_t" v-if="record_status===10">-->
            <!--<view class="button button_s">-->
            <!--<text class="iconfont begin_b" style="position: relative;right:-4upx">&#xe619;</text>-->
            <!--</view>-->
            <!--<text class="button_s_t">试听</text>-->
            <!--</view>-->


            <view class="button_box_list relative_t" v-if="record_status>0 " @click="cancelRecord">
                <view class="button button_s" @click="stop_record">
                    <!--重新录制-->
                    <text class="iconfont begin_b">&#xe620;</text>
                </view>
                <text class="button_s_t font-regular" style="width: 104upx;text-align: center;">重录</text>
            </view>
            <view class="button_box_list" v-if="record_status===10"  @click="playRecord">
                <view class="button button_b">
                    <text class="iconfont begin_r"  style="margin-left:16upx" >&#xe619;</text>
                </view>
                <text class="button_b_t font-medium" style="width: 104upx;text-align: center;">试听&nbsp;&nbsp;</text>
                <text class="button_s_t font-regular">{{timeToString(duration)}}</text>
            </view>

<!--            进行中-->
            <view class="button_box_list" v-if="record_status===11" @click="pausePlay">
                <view class="button button_b">
                    <text class="iconfont begin_r">&#xe61f;</text>
                </view>
                <text class="button_b_t font-medium" >暂停</text>
                <text class="button_s_t font-regular">{{timeToString(duration)}}</text>
            </view>

            <view class="button_box_list" v-if="record_status===1" @click="pauseRecord">
                <view class="button button_b">
                    <text class="iconfont begin_r">&#xe61f;</text>
                </view>
                <text class="button_b_t font-medium" >暂停</text>
                <text class="button_s_t font-regular">{{timeToString(duration)}}</text>
            </view>
            <view class="button_box_list" v-if="record_status===5" @click="reRecord">
                <view class="button button_b">
                    <text class="iconfont begin_r" style="position: relative;left: 3px">&#xe619;</text>
                </view>
                <text class="button_b_t font-medium">继续</text>
                <text class="button_s_t font-regular">{{ timeToString(duration)}}</text>
            </view>
            <!---->
            <!--<view class="button_box_list relative_t" v-if="record_status==10" @click="playRecord">-->
                <!--<view class="button button_s">-->
                    <!--<text class="iconfont begin_w">&#xe61b;</text>-->
                <!--</view>-->
                <!--<text class="button_s_t">发布</text>-->
            <!--</view>-->

            <view class="button_box_list relative_t" v-if="record_status>0 && record_status<10 " @click="completeRecord">
                <view class="button button_s">
                    <text class="iconfont begin_w">&#xe61b;</text>
                </view>
                <text class="button_s_t" style="width: 104upx;text-align: center;">完成&nbsp;&nbsp;</text>
            </view>

            <view class="button_box_list relative_t" v-if="record_status>=10 " @click="saveRecord">
                <view class="button button_s">
                    <text class="iconfont begin_w">&#xe61b;</text>
                </view>
                <text class="button_s_t" style="width: 104upx;text-align: center;">发布</text>
            </view>


        </view>


        <!--阴影-->
        <view class="button-shadow"></view>

        <!--        倒计时-->
        <view class="count_down">
            <uni-popup ref="popup_d" :maskClick="false" type="center">
                <view class="popub_box">
                    <text class="num">{{countDown}}</text>
                    <text class="text">秒后开始录制</text>
                </view>
            </uni-popup>
        </view>
        <!--        发布-->

        <record-save :show="dialog_save" @cancel="dialog_save=false" :title="title" :name="user.name" :thumb="subject.thumb_link.large"  @submit="record_save"></record-save>
        <!--        是否分享-->
        <record-share :show="dialog_share" desc="读的很棒哦！分享给大家听吧～"  title="作品上传成功" :record_id="record_id" :subject_id="subject_id" @cancel="dialog_share=false" ></record-share>
        <!--        确定是否重新录制-->

        <view class="return_record">
            <uni-popup ref="popup_r02" :maskClick="false" type="center">
                <view class="popub_box">
                    <text class="iconfont cancel_icon" @click="close_return02">&#xe615</text>
                    <view>你的录音未保存,确认放弃吗？</view>
                </view>
                <view class="popub_btn">
                    <view class="fa_btn confirm">重新录制</view>
                    <view class="fa_btn cancel">确认放弃</view>
                </view>
            </uni-popup>
        </view>

        <!--        确定重新录制-->
        <view class="return_record">
            <uni-popup ref="popup_r01" :maskClick="false" type="center">
                <view class="popub_box">
                    <text class="iconfont cancel_icon" @click="close_return01">&#xe615</text>
                    <view>确定要重新录制吗？</view>
                </view>
                <view class="popub_btn">
                    <view class="fa_btn confirm">重新录制</view>
                    <view class="fa_btn cancel">取消</view>
                </view>
            </uni-popup>
        </view>

        <view style="position: fixed;bottom: 20upx;right: 20upx;color: #fff;font-size: 26upx" class="font-regular">
            {{current+1}}/{{info.length}}
        </view>

    </view>
</template>

<script>
  import {uniSwiperDot, uniPopup} from "@dcloudio/uni-ui"
  import RecordSave from "../../dialog/record/save"
  import RecordShare from "../../dialog/record/share"
  import RecordPoster from "../../dialog/record/poster"
  import Request from '@/utils/request.js'
  import CourseIndex from "../../../components/course/index"

  const recorderManager = uni.getRecorderManager();
  const innerAudioContext = uni.createInnerAudioContext();
  const bgm = uni.createInnerAudioContext();


  export default {
    components: {CourseIndex, RecordPoster, RecordShare, RecordSave, uniSwiperDot, uniPopup},
    data() {
      return {
        subject_id : 0,
        info: [], //幻灯片
        showl:true,
        subject:{},//脚本
        dotsStyles: {
          width: 8,
          height: 8,
          bottom: 0,
          selectedBackgroundColor: '#fcb300',
          backgroundColor: '#ffffff',
          border: '1px solid #ffffff',
          selectedBorder: '1px solid #ffffff',
        },
        action:[],//录制的幻灯片脚本

        voiceTmpPath: '',//录音文件地址
        voicePath: '',//录音文件地址
        ipad:'iphone',
        diyContent:'',
        sliderScript:[],

        dialog_save: false,
        dialog_share: false,

        title:'',

        record_status:0,//0未启动 1启动 5暂停 10完成 11试听中
        countDown: 3,//
        user:{},
        current: 0,
        mode: 'dot',
        indicatorDots: true,
        autoplay: false,
        interval: null,
        duration: 0,
        swiperHeight: '0px',
        sharePost:'',
        record_id:0,//录完之后哦的
      }
    },
    beforeDestroy() {
      clearInterval(this.interval);
    },
    /**
     * 分享自定义
     */
    onShareAppMessage(res) {

      if (res.from === 'button') {// 来自页面内分享按钮
        console.log(res.target)
      }
      console.log(this.subject.thumb_link.large);
      return {
        title: this.title,
        path: 'pages/index/index?id='+this.record_id,
        imageUrl:this.subject.thumb_link.large,
        desc:this.diyContent,
      }
    },
    onLoad(param) {
      console.log(param,'onload')
      this.subject_id=param.id;
      let self = this;
      recorderManager.onStop(function (res) {
        console.log('recorder stop' + JSON.stringify(res));
        self.voiceTmpPath = res.tempFilePath;
        bgm.stop();
      });

      this.user = uni.getStorageSync('user');

      this.getSubjectInfo();



    },
    onUnload(){
      console.log('录音页面卸载');
      this.stop_record();
    },
    mounted() {
      let _self = this;
      uni.getSystemInfo({
        success: function (res) {
          if (res.windowWidth / res.windowHeight > 0.7) {
            _self.ipad = 'ipad';
          }
          console.log(ipad,_self.ipad);
        }
      });


      console.log(process.env.VUE_APP_HOST);
      this.interval = setInterval(() => {
        if (this.record_status == 1) {
          this.duration += 1;
        }
      }, 1000);
      // this.$refs.popup_i.open()
      // this.$refs.popup_d.open()
      // this.$refs.popup_s.open()
      // this.$refs.popup.open()
      // this.$refs.popup_r01.open()
      // this.$refs.popup_r02.open()

      uni.getSystemInfo({
        success: function (res) {
          _self.swiperHeight = res.windowHeight + 'px';
          _self.dotsStyles.bottom = res.windowHeight - 30;
        }
      });
    },
    methods: {

        //取消试听播放
       pausePlay(){
         this.record_status=10;
         innerAudioContext.stop();
         bgm.stop();
       },
      getSubjectInfo() {
        Request.get('/tape/subject/' + this.subject_id).then((data) => {
          this.subject = data.data;
          bgm.src = data.data.bgm_link;
          this.info = [];
          data.data.images_link.large.forEach((val) => {
            this.info.push({'url': val})
          });
          bgm.loop = true;
          bgm.title = data.data.title;
          bgm.seek = 0;
          bgm.volume = 0.3
          console.log(data);
          this.title = data.data.title;
          uni.setNavigationBarTitle({
            title: data.data.title
          });
        })
      },

      //发布类型
      record_save(param) {
        this.dialog_save = false;
        this.diyContent = param.content;
        uni.showLoading();
        console.log(this.voicePath,'voicePath');
        Request.post('/tape/record',{
          'subject_id':this.subject_id,
          'time':this.duration+1,
          'action':this.action,
          'content':this.diyContent,
          'original_record':this.voicePath.filePath
        }).then((data)=>{
          uni.hideLoading();
          this.record_id=data.data.id;
          this.dialog_share = true;
        });


      },

      //放弃录制
      stop_record() {
        console.log('录音结束');
        recorderManager.stop()
      },

      /**
       * 秒转分钟
       * @param time
       * @returns {string|string}
       */
      timeToString(time) {
        let string = '';
        if (time > 60) {
          string = time;
          time =  time % 60;
          if(time<10)
            time = '0'+time;
          string = parseInt(string / 60) + ':' +time;

        } else {
          if(time<10)
            time = '0'+time
          string = '00:' + time;
        }
        return string
      },

      beginRecord() {  // 开始录制前倒计时
        this.voicePath=null;
        this.action=[];
        let _this = this;
        //判断权限,倒计时
        uni.authorize({
          scope: 'scope.record',
          success() {
            _this.$refs.popup_d.open()
            _this.countDown = 3;
            setTimeout(() => {
              _this.countDown = 2;
            }, 1000)
            setTimeout(() => {
              _this.countDown = 1;
            }, 2000);
            setTimeout(() => {
              //启动录音
              _this.$refs.popup_d.close();
              _this.record_status = 1;
              // bgm.volume=0.1//音量
              // bgm.play();
              bgm.stop();
              recorderManager.start({
                'duration': 600000,
                'format': 'mp3',
              });
              _this.duration = 0;
            }, 3000)
          }
        })
      },


      //  完成录制
      // 第一次点击是完成录制
      completeRecord() {
        this.record_status = 10;
        console.log('录音结束');
        recorderManager.stop()

      },

      // 发布
      saveRecord() {
        // this.dialog_save = true;
        // return ;
        //如果已经上传过了
        this.pausePlay();
        if(this.voicePath){
          this.dialog_save = true;
        }else {
          uni.showLoading();
          uni.uploadFile({
            url: process.env.VUE_APP_HOST + '/tape/record/upload', //仅为示例，非真实的接口地址
            filePath: this.voiceTmpPath,
            name: 'file',
            success: (res) => {
              //上传
              this.dialog_save = true;
              let data = JSON.parse(res.data);
              this.voicePath = data.data;
              console.log(this.voicePath)
              uni.hideLoading();
            }
          });
        }


      },

      //试听的
      playRecord() {
        if (this.voiceTmpPath) {
          this.record_status=11;
          innerAudioContext.src = this.voiceTmpPath;
          innerAudioContext.play();
          bgm.play();
        }
      },

      //暂停
      pauseRecord() {
        console.log('录音暂停');
        recorderManager.pause()
        // bgm.pause();
        this.record_status = 5;
      },

      cancelRecord() {
        this.record_status = 0;
        bgm.stop();
      },
      reRecord() {
        console.log('录音恢复');
        recorderManager.resume()
        // bgm.play();
        this.record_status = 1;
      },


      // share() {  // 小程序分享都是保存绘制的图片
      //   this.$refs.popup_s.close()
      //   this.$refs.popup_i.open()
      // },
      // close_return01() {
      //   this.$refs.popup_r01.close()
      // },
      // close_return02() {
      //   this.$refs.popup_r02.close()
      // },
      change(e) {
        console.log(e,'slider')
        //开始录音后 只能一页页翻
        this.current = e.detail.current;
        if(this.record_status>0) {
            this.action.push({
              time:this.duration,
              url:this.info[this.current].url,
              current:this.current
            })
        }
      },

    }
  }
</script>


<style lang="scss">
    .place-placeholde {
        font-size: $uni-font-size-14;
        color: $uni-color-876a48;
        opacity: 0.5;
    }

    .record {
        position: relative;
        width: 100vw;
        height: 100vh;
        overflow: hidden;

        .iconfont{
            position: relative;
            top:2upx
        }
        .count_down {
            .uni-popup__wrapper.uni-custom.center .uni-popup__wrapper-box {
                top: -150upx;
                width: 250upx;
                height: 250upx;
                border-radius: 50%;
                background-color: rgba(0, 0, 0, 0.6);
                overflow: hidden;
                position: relative;
            }

            .uni-popup__wrapper.uni-custom .uni-popup__wrapper-box {
                padding: 0upx;
            }
            .popub_box {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                .num {
                    font-size: 128upx;
                    font-weight: 600;
                    color: $uni-color-fffbf0;
                }
                .text {
                    font-size: $uni-font-size-13;
                    color: #ffffff;
                }
            }
        }

        //录音确认
        .return_record {
            .uni-popup__wrapper.uni-custom.center .uni-popup__wrapper-box {
                top: -150upx;
                width: 500upx;
                height: 320upx;
                border-radius: 20upx;
                overflow: hidden;
                position: relative;
            }
            .uni-popup__wrapper.uni-custom .uni-popup__wrapper-box {
                padding: 0upx;
            }
            .popub_box {
                box-sizing: border-box;
                padding: 61upx 114upx 0;
                font-size: $uni-font-size-base;
                color: $uni-color-664e37;
                line-height: 50upx;
                text-align: center;
                .cancel_icon {
                    position: absolute;
                    top: 14upx;
                    right: 24upx;
                    font-size: 30upx;
                    color: $uni-color-876a48;
                    transform: rotate(-45deg);
                }
            }
            .popub_btn {
                width: 100%;
                height: 100upx;
                position: absolute;
                bottom: 0upx;
                left: 0upx;
                background-color: #eeeeee;
                display: flex;
                font-size: $uni-font-size-base;
                .fa_btn {
                    width: 50%;
                    height: 100upx;
                    line-height: 100upx;
                    text-align: center;
                }
                .cancel {
                    background-color: $uni-color-fffbf0;
                    color: $uni-color-664e37;
                }
                .confirm {
                    background-color: $uni-color-fcb300;
                    color: #ffffff;
                }
            }
        }
        .ipad{
            max-width: 80vw;
            max-height: 100vh;
            margin-left: 10vw;
        }
        .img {
            width: 750upx;
            height: 1206upx;
        }
        .button_box {

            height: 268upx!important;
            background:linear-gradient(rgba(112,112,112,0),rgba(112,112,112,0.3), rgba(85,85,85,0.5));
            box-sizing: border-box;
            position: fixed;
            bottom: 0upx;
            left: 0upx;
            width: 100%;
            padding: 0 114upx;
            padding-bottom: 22upx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .relative_t {
                position: relative;
                top: -24upx;
            }
            .button_box_list {
                display: flex;
                flex-direction: column;
                align-items: center;
                color: #ffffff;
                .button {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-align: center;
                    font-size: 20upx;
                    border-radius: 50%;
                    background-color: $uni-color-fcb300;
                    opacity: 0.7;
                    margin-bottom: 14upx;
                    .begin_r {
                        font-size: 46upx;
                    }
                    .begin_l {
                        font-size: 34upx;
                    }
                    .begin_b {
                        font-size: 26upx;
                    }
                    .begin_s {
                        font-size: 45upx;
                    }
                    .begin_w {
                        font-size: 26upx;
                    }
                }
                .button_b {
                    width: 140upx;
                    height: 140upx;
                }
                .button_s {
                    width: 80upx;
                    height: 80upx;
                    background: #fdc63e;
                }
                .button_s_t {
                    font-size: $uni-font-size-13;
                    line-height: 38upx;
                }
                .button_s_b {
                    font-size: $uni-font-size-base;
                    line-height: 48upx;
                }
            }

        }
        .button_begin {
            justify-content: center;
            padding-bottom: 61upx;

        }

    }
</style>
